package durst.action.account;

import java.sql.SQLException;
import java.util.List;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import durst.action.CalendarBasicAction;
import durst.data.Account;
import durst.data.Friend;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.AccountDao;
import durst.data.dao.impl.FriendDao;

public class AddFriendAction extends CalendarBasicAction {
	@Validate(required = true, mask="\\w+")
	private String friend;
	
	@SuppressWarnings("unchecked")
	@DefaultHandler
	public Resolution add() throws SQLException {
		AccountDao<Account, Integer> dao = (AccountDao<Account, Integer>)DaoFactory.getInstance().createDao(Account.class);
		List<Account> accounts = dao.queryByUsernameOrEmail(friend, friend);

		if (accounts.size() > 0) {
			FriendDao<Friend, Integer> friendDao = (FriendDao<Friend, Integer>) DaoFactory.getInstance().createDao(Friend.class);
			List<Account> friends = friendDao.findFriends(context.getAccount(), null, "", "");
			for (Account account : accounts)
				if (!friends.contains(account))
					friendDao.create(new Friend(context.getAccount(), account));
		}
		
		return new RedirectResolution(ManageAccountActionBean.class);
	}
	
	public String getFriend() {
		return friend;
	}
	
	public void setFriend(String friend) {
		this.friend = friend;
	}
}
